package com.example.orchid.paper.util;

import android.os.Bundle;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * UrlUtils
 * Created by Orchid on 2015-10-13.
 */
public class UrlUtils {

    /**
     * 将Key-value转换成用&号链接的URL查询参数形式。
     *
     * @param params
     * @return
     */
    public static String encodeUrl(Bundle params) {
        if (params == null) {
            return "";
        }
        ArrayList<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String key : params.keySet()) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            if (params.getString(key) != null) {
                try {
                    sb.append(URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.getString(key), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

        }
        return sb.toString();
    }
}
